<!-- 个人中心页面 -->
<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 个人信息卡片 -->
      <el-col :span="8">
        <el-card class="profile-card">
          <template #header>
            <div class="card-header">
              <span>个人信息</span>
              <el-button
                type="primary"
                link
                @click="editMode = true"
                v-if="!editMode"
              >
                编辑
              </el-button>
              <el-button type="success" link @click="handleSave" v-else>
                保存
              </el-button>
            </div>
          </template>

          <el-form ref="profileForm" :model="profileForm" :disabled="!editMode">
            <el-form-item label="用户名">
              <el-input v-model="profileForm.username" disabled />
            </el-form-item>
            <el-form-item label="真实姓名">
              <el-input v-model="profileForm.realName" />
            </el-form-item>
            <el-form-item label="角色">
              <el-input v-model="profileForm.role" disabled />
            </el-form-item>
            <el-form-item label="班级" v-if="profileForm.role === 'student'">
              <el-input v-model="profileForm.className" />
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>

      <!-- 修改密码卡片 -->
      <el-col :span="8">
        <el-card class="password-card">
          <template #header>
            <div class="card-header">
              <span>修改密码</span>
            </div>
          </template>

          <el-form
            ref="passwordForm"
            :model="passwordForm"
            :rules="passwordRules"
            label-width="100px"
          >
            <el-form-item label="原密码" prop="oldPassword">
              <el-input
                v-model="passwordForm.oldPassword"
                type="password"
                show-password
              />
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword">
              <el-input
                v-model="passwordForm.newPassword"
                type="password"
                show-password
              />
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input
                v-model="passwordForm.confirmPassword"
                type="password"
                show-password
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleChangePassword">
                修改密码
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>

      <!-- 成绩统计卡片 -->
      <el-col :span="8" v-if="profileForm.role === 'student'">
        <el-card class="statistics-card">
          <template #header>
            <div class="card-header">
              <span>成绩统计</span>
            </div>
          </template>

          <div class="statistics-content">
            <div class="chart-container" ref="chartRef"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { getUserInfo, updateUserInfo, changePassword } from "@/api/user";
import { getUserScoreTrend } from "@/api/exam";
import * as echarts from "echarts";

const editMode = ref(false);
const chartRef = ref(null);
let chart = null;

const profileForm = reactive({
  username: "",
  realName: "",
  role: "",
  className: "",
});

const passwordForm = reactive({
  oldPassword: "",
  newPassword: "",
  confirmPassword: "",
});

const validatePass = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请输入新密码"));
  } else {
    if (passwordForm.confirmPassword !== "") {
      if (value !== passwordForm.confirmPassword) {
        callback(new Error("两次输入密码不一致"));
      }
    }
    callback();
  }
};

const validatePass2 = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请再次输入密码"));
  } else if (value !== passwordForm.newPassword) {
    callback(new Error("两次输入密码不一致"));
  } else {
    callback();
  }
};

const passwordRules = {
  oldPassword: [{ required: true, message: "请输入原密码", trigger: "blur" }],
  newPassword: [
    { required: true, validator: validatePass, trigger: "blur" },
    { min: 6, message: "密码长度不能小于6个字符", trigger: "blur" },
  ],
  confirmPassword: [
    { required: true, validator: validatePass2, trigger: "blur" },
  ],
};

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const data = await getUserInfo();
    profileForm.username = data.username;
    profileForm.realName = data.realName;
    profileForm.role = data.role;
    profileForm.className = data.className;
  } catch (error) {
    console.error("获取用户信息失败：", error);
  }
};

// 保存个人信息
const handleSave = async () => {
  try {
    await updateUserInfo(profileForm);
    ElMessage.success("保存成功");
    editMode.value = false;
  } catch (error) {
    console.error("保存失败：", error);
  }
};

// 修改密码
const handleChangePassword = async () => {
  try {
    await changePassword(passwordForm);
    ElMessage.success("密码修改成功");
    passwordForm.oldPassword = "";
    passwordForm.newPassword = "";
    passwordForm.confirmPassword = "";
  } catch (error) {
    console.error("修改密码失败：", error);
  }
};

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return;
  chart = echarts.init(chartRef.value);
};

// 更新图表数据
const updateChart = async () => {
  if (!chart || profileForm.role !== "student") return;
  try {
    const records = await getUserScoreTrend({ limit: 10 });
    const dates = records.map((r) => r.createdTime.substring(0, 10));
    const scores = records.map((r) => r.score);

    chart.setOption({
      title: {
        text: "最近考试成绩趋势",
      },
      tooltip: {
        trigger: "axis",
      },
      xAxis: {
        type: "category",
        data: dates,
      },
      yAxis: {
        type: "value",
        min: 0,
        max: 100,
      },
      series: [
        {
          name: "分数",
          type: "line",
          data: scores,
          markLine: {
            data: [{ type: "average", name: "平均分" }],
          },
        },
      ],
    });
  } catch (error) {
    console.error("获取成绩趋势失败：", error);
  }
};

onMounted(() => {
  fetchUserInfo();
  initChart();
  updateChart();
});
</script>

<style scoped>
.profile-card,
.password-card,
.statistics-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.statistics-content {
  height: 300px;
}

.chart-container {
  width: 100%;
  height: 100%;
}
</style>
